"""
统一响应模型
参考字节火山引擎 API 设计
"""
from pydantic import BaseModel, Field
from typing import Optional, Any, Generic, TypeVar
from datetime import datetime

# 泛型类型变量
T = TypeVar('T')


class ResponseMetadata(BaseModel):
    """响应元数据"""
    RequestId: str = Field(..., description="请求ID，用于问题排查")
    Action: str = Field(..., description="具体接口名称")
    Version: str = Field(default="v1", description="接口版本")
    Service: str = Field(..., description="服务模块名称")
    Timestamp: Optional[str] = Field(default=None, description="响应时间戳")
    
    class Config:
        json_schema_extra = {
            "example": {
                "RequestId": "123e4567-e89b-12d3-a456-426614174001",
                "Action": "ListCluster",
                "Version": "v1",
                "Service": "Product",
                "Timestamp": "2025-10-16T10:30:00Z"
            }
        }


class ErrorInfo(BaseModel):
    """错误信息"""
    Code: str = Field(..., description="业务错误码")
    Message: str = Field(..., description="错误信息")
    Detail: Optional[str] = Field(default=None, description="详细错误说明")
    
    class Config:
        json_schema_extra = {
            "example": {
                "Code": "100001",
                "Message": "System Error",
                "Detail": "database name cannot be empty"
            }
        }


class SuccessResponse(BaseModel, Generic[T]):
    """成功响应"""
    ResponseMetadata: ResponseMetadata
    Result: T
    
    class Config:
        json_schema_extra = {
            "example": {
                "ResponseMetadata": {
                    "RequestId": "123e4567-e89b-12d3-a456-426614174001",
                    "Action": "ListCluster",
                    "Version": "v1",
                    "Service": "Product"
                },
                "Result": {}
            }
        }


class ErrorResponse(BaseModel):
    """错误响应"""
    ResponseMetadata: ResponseMetadata
    Error: ErrorInfo
    
    class Config:
        json_schema_extra = {
            "example": {
                "ResponseMetadata": {
                    "RequestId": "123e4567-e89b-12d3-a456-426614174001",
                    "Action": "ListCluster",
                    "Version": "v1",
                    "Service": "Product"
                },
                "Error": {
                    "Code": "100001",
                    "Message": "System Error",
                    "Detail": "database name cannot be empty"
                }
            }
        }


# 业务错误码定义
class ErrorCode:
    """统一错误码"""
    # 系统级错误 (10xxxx)
    SYSTEM_ERROR = "100001"
    INTERNAL_ERROR = "100002"
    SERVICE_UNAVAILABLE = "100003"
    
    # 认证相关错误 (20xxxx)
    INVALID_TOKEN = "200001"
    TOKEN_EXPIRED = "200002"
    UNAUTHORIZED = "200003"
    FORBIDDEN = "200004"
    
    # 用户相关错误 (30xxxx)
    USER_NOT_FOUND = "300001"
    USER_ALREADY_EXISTS = "300002"
    INVALID_PASSWORD = "300003"
    INVALID_EMAIL = "300004"
    USER_DISABLED = "300005"
    EMAIL_ALREADY_EXISTS = "300006"
    USERNAME_ALREADY_EXISTS = "300007"
    
    # 数据相关错误 (40xxxx)
    RESOURCE_NOT_FOUND = "400001"
    INVALID_PARAMETER = "400002"
    PERMISSION_DENIED = "400003"
    DUPLICATE_RESOURCE = "400004"
    
    # 业务逻辑错误 (50xxxx)
    OPERATION_FAILED = "500001"
    INVALID_OPERATION = "500002"
    
    # 证书相关错误 (60xxxx)
    CERT_DOMAIN_INVALID = "600001"
    CERT_TOO_MANY_SANS = "600002"
    CERT_DNS_CREDENTIAL_NOT_FOUND = "600003"
    CERT_ALREADY_EXISTS = "600004"
    CERT_NOT_FOUND = "600005"
    CERT_APPLY_FAILED = "600006"
    CERT_RENEW_FAILED = "600007"
    CERT_NOT_READY = "600008"
    DNS_RECORD_NOT_FOUND = "600009"
    DNS_VALIDATION_FAILED = "600010"


class ErrorMessage:
    """错误信息映射"""
    messages = {
        ErrorCode.SYSTEM_ERROR: "系统错误",
        ErrorCode.INTERNAL_ERROR: "内部错误",
        ErrorCode.SERVICE_UNAVAILABLE: "服务不可用",
        
        ErrorCode.INVALID_TOKEN: "无效的Token",
        ErrorCode.TOKEN_EXPIRED: "Token已过期",
        ErrorCode.UNAUTHORIZED: "未授权",
        ErrorCode.FORBIDDEN: "禁止访问",
        
        ErrorCode.USER_NOT_FOUND: "用户不存在",
        ErrorCode.USER_ALREADY_EXISTS: "用户已存在",
        ErrorCode.INVALID_PASSWORD: "密码错误",
        ErrorCode.INVALID_EMAIL: "邮箱格式错误",
        ErrorCode.USER_DISABLED: "用户已被禁用",
        ErrorCode.EMAIL_ALREADY_EXISTS: "邮箱已被使用",
        ErrorCode.USERNAME_ALREADY_EXISTS: "用户名已被使用",
        
        ErrorCode.RESOURCE_NOT_FOUND: "资源不存在",
        ErrorCode.INVALID_PARAMETER: "参数错误",
        ErrorCode.PERMISSION_DENIED: "权限不足",
        ErrorCode.DUPLICATE_RESOURCE: "资源已存在",
        
        ErrorCode.OPERATION_FAILED: "操作失败",
        ErrorCode.INVALID_OPERATION: "无效操作",
        
        ErrorCode.CERT_DOMAIN_INVALID: "域名格式无效",
        ErrorCode.CERT_TOO_MANY_SANS: "SAN 域名过多",
        ErrorCode.CERT_DNS_CREDENTIAL_NOT_FOUND: "DNS 凭据不存在",
        ErrorCode.CERT_ALREADY_EXISTS: "证书已存在",
        ErrorCode.CERT_NOT_FOUND: "证书不存在",
        ErrorCode.CERT_APPLY_FAILED: "证书申请失败",
        ErrorCode.CERT_RENEW_FAILED: "证书续签失败",
        ErrorCode.CERT_NOT_READY: "证书未就绪",
        ErrorCode.DNS_RECORD_NOT_FOUND: "DNS 记录未找到",
        ErrorCode.DNS_VALIDATION_FAILED: "DNS 验证失败",
    }
    
    @classmethod
    def get(cls, code: str) -> str:
        """获取错误信息"""
        return cls.messages.get(code, "未知错误")

